import { _decorator, Component, director, Node, Prefab } from 'cc';
import { ElementAction } from './ElementAction';

import { LayerAction } from './LayerAction';
import { Global } from './Global';
import { PinAction } from './PinAction';
import { DataModel } from './DataModel';
import { events } from './Enums';
import { CatColorRules } from './CatColorRules';
const { ccclass, property } = _decorator;

@ccclass('LevelAction')
export class LevelAction extends Component {

    static Inst: LevelAction = null;

    onLoad() {
        LevelAction.Inst = this;
    }

    start() {
    }


    get_lvl(): number {
        let arr = this.node.name.split("_");
        // console.log("split get_lvl>>>>>:", arr);
        return Number(arr[1].trim());
    }

    get_hole_num(): number {
        let _arr = []
        let hole_num: number = 0;
        this.node.children.forEach(layer_node => {
            let num = this.getLayAct(layer_node).get_hole_num();
            hole_num += num;
            
            _arr.push(num)
        });
        console.log("孔:",_arr.reverse())

        return hole_num;
    }

    getLayAct(n: Node): LayerAction {
        let layAct = n.getComponent(LayerAction);
        if (!layAct) layAct = n.addComponent(LayerAction)
        return layAct;
    }

    public init_level() {
        //每次开始把基础颜色打乱
        DataModel.random_base_color();

        console.log("原始颜色：", DataModel.base_color_arr)

        DataModel.generate_lvl_color_arr(Global.cur_lvl_index + 4);
        // init every layer
        this.node.children.forEach(layer_node => {
            // console.log("init_level this.node>>>>>:", this.node);
            this.getLayAct(layer_node).init_layer();
        });

        //
        let color_pin_arr = [];
        let color_cat_arr = [];
        let total_hole_num = this.get_hole_num();//钉子总数
        let need_slot_num = total_hole_num / 3;
        for (let i = 0; i < need_slot_num; i++) {
            let base = DataModel.get_lvl_color();
            let b = base.clone();
            //console.log(i , b); //sb error
            color_pin_arr.push(b);
            color_pin_arr.push(b);
            color_pin_arr.push(b);
            color_cat_arr.push(base);
        }

        color_pin_arr.sort(() => {
            return 0.5 - Math.random();
        });
        color_cat_arr.sort(() => {
            return 0.5 - Math.random();
        });


        console.log(" color_cat_arr：", color_cat_arr.length, " *3 = color_pin_arr：", color_pin_arr.length);

        this.node.children.forEach(layer_node => {
            // console.log("init_level this.node>>>>>:", this.node);
            layer_node.getComponent(LayerAction).init_pin(color_pin_arr);
        });
        // console.log("need pin  num：",need_slot_num);
        CatColorRules.set_cat_color(color_cat_arr);
        console.log("--> ", Global.layer_empty_action)
        Global.layer_empty_action.init_empty();
        Global.layer_cat_action.init_cat();

        //本关，钉子总数
        Global.init_pin_info(total_hole_num);
        console.log("电池总数 or 孔的总数：", total_hole_num)

        director.on(events.update_element, this.update_element, this);

        //--->隐藏一部分板子，不全部显示
        this.scheduleOnce(() => {
            this.set_default_layer();
        }, 0.2)

    }


    public init_level_config(bat_data: number[], bat_c_data: number[]) {
        //console.log("原始颜色：",DataModel.base_color_arr)

        //console.log("反转后：",bat_data.length , "bat_data：",bat_data)
        //console.log(bat_c_data.length ,"bat_c_data：",bat_c_data)

        // init every layer 添加 LayerAction 脚本
        this.node.children.forEach(layer_node => {
            this.getLayAct(layer_node).init_layer();
        });

        let color_pin_arr = [];
        let color_cat_arr = [];

        let total_hole_num = this.get_hole_num();//钉子总数
        console.log("电池总数 or 孔的总数：", total_hole_num)

        if (total_hole_num % 3 != 0) {
            console.warn("板子存在问题，孔数不是3的倍数");
        }
        if (bat_data.length != total_hole_num) {
            console.warn("layer json 配置存在问题，数量应与 电池or孔 数量相等", total_hole_num, bat_data.length);
        }

        // if (bat_c_data.length * 3 != bat_data.length) {
        //     console.log("仓数：",bat_c_data.length ," * 3 应= 电池数：", bat_data.length);
        // }

        //3个电池 进一个仓
        let dc_num = 3;
        let dc_c_index = 0;
        for (let i = 0; i < bat_data.length; i++) {
            let base = DataModel.base_color_arr[bat_data[i]];
            let b = base.clone();
            color_pin_arr.push(b);

            dc_num--;
            if (dc_num <= 0) {// 3个电池加 1个仓
                // 改 25.7.9.18.11 预处理数据
                // let base_c = DataModel.base_color_arr[bat_c_data[dc_c_index]];
                // color_cat_arr.push(base_c.clone());
                dc_num = 3;
                dc_c_index++;
            }
        }

        this.node.children.forEach(layer_node => {
            layer_node.getComponent(LayerAction).init_pin(color_pin_arr);
        });

        // 改 25.7.9.18.11 set数据
        // CatColorRules.set_cat_color(color_cat_arr);

        Global.layer_empty_action.init_empty();
        Global.layer_cat_action.init_cat();

        //本关，钉子总数
        Global.init_pin_info(total_hole_num);

        director.on(events.update_element, this.update_element, this);

        //--->隐藏一部分板子，不全部显示
        this.scheduleOnce(() => {
            this.set_default_layer();
        }, 0.2)

    }

    set_default_layer() {
        //默认都是不显示的
        for (let i = this.node.children.length - 1; i >= 0; i--) {
            let layer_action = this.node.children[i].getComponent(LayerAction);

            layer_action.node.active = false;
        }
        this.update_element();

        Global.layer_root_action.showRoot();
    }

    /** 更新板子 */
    update_element() {
        //console.log("移除板子")

        //默认显示4层
        let default_show_layer_num = 4;
        let show_num = 0;

        let _index = -1

        for (let i = this.node.children.length - 1; i >= 0; i--) {
            let layer_action = this.node.children[i].getComponent(LayerAction);
            if (!layer_action) break;
            if (layer_action.get_element_size() <= 0) {
                continue;
            }
            if (show_num < default_show_layer_num) {
                layer_action.layer_active(true);
                show_num++;

            } else {
                if (_index == -1) _index = i;

                //第5层 开始隐藏
                layer_action.layer_active(false);
            }
        }

        if (_index >= this.node.children.length || _index == -1) return;
        let show_last_layer = this.node.children[_index].getComponent(LayerAction);
        show_last_layer.show_outline();
    }

    get_pin_color(): PinAction[] {
        let arr: PinAction[] = [];
        // this.node.children.forEach(layer_node => {
        //     layer_node.getComponent(LayerAction)?.get_pin_color(arr);
        // });
        for (let i = this.node.children.length - 1; i >= 0; i--) {
            let layer_action = this.node.children[i].getComponent(LayerAction);
            layer_action?.get_pin_color(arr);
        }
        return arr
    }

    /** 获取层级电池 */
    get_pin_color_allLayer(){
        let arrs: PinAction[][] = [];
        for (let i = this.node.children.length - 1; i >= 0; i--) {
            let arr:PinAction[] = []
            let layer_action = this.node.children[i].getComponent(LayerAction);
            layer_action?.get_pin_color(arr);
            arrs.push(arr)
        }
        return arrs
    }

}

